package com.kyh.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;

public class ImgUtil {
	

//	public static void main(String[] args) {
//		String url = "http://fileaw.yijuran.com/upload/manage/2018/12/29/104116329.jpg";
//		String imgLocalPathAndName = "C:\\Users\\Administrator\\Desktop\\1.jpg";
//		downloadPicture(url, imgLocalPathAndName);
//	}

	// 链接url下载图片
	public static void downloadPicture(String urlImg, String imgLocalPathAndName) {
		Long aa = System.currentTimeMillis();
		System.out.println(aa);
		try {
			URL url = new URL(urlImg);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());

			FileOutputStream fileOutputStream = new FileOutputStream(new File(imgLocalPathAndName));
			ByteArrayOutputStream output = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024];
			int length;

			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			fileOutputStream.write(output.toByteArray());
			dataInputStream.close();
			fileOutputStream.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Long bb = System.currentTimeMillis();
		System.out.println(bb-aa);
	}
	
		/**
	     * 读取远程url图片,得到宽高
	     * @param imgurl 图片路径
	     * @return [0] 宽  [1]高
	     */
	public static int[] getImgWH(String imgurl) {
	        boolean b=false;
	        try {
	            //实例化url
	            URL url = new URL(imgurl);
	            //载入图片到输入流
	            java.io.BufferedInputStream bis = new BufferedInputStream(url.openStream());
	            //实例化存储字节数组
	            byte[] bytes = new byte[100];
	            //设置写入路径以及图片名称
	            OutputStream bos = new FileOutputStream(new File("pic.jpg"));
	            int len;
	            while ((len = bis.read(bytes)) > 0) {
	                bos.write(bytes, 0, len);
	            }
	            bis.close();
	            bos.flush();
	            bos.close();
	            //关闭输出流
	            b=true;
	        } catch (Exception e) {
	            //如果图片未找到
	            b=false;
	        }
	        int[] a = new int[2];
	        if(b){//图片存在
	            //得到文件
	            java.io.File file = new java.io.File("pic.jpg");
	            BufferedImage bi = null;
	            boolean imgwrong=false;
	            try {
	                //读取图片
	                bi = javax.imageio.ImageIO.read(file);
	                try{
	                    //判断文件图片是否能正常显示,有些图片编码不正确
	                    imgwrong=true;
	                }catch(Exception e){
	                    imgwrong=false;
	                }
	            } catch (IOException ex) {
	                ex.printStackTrace();
	            }
	            if(imgwrong){
	                a[0] = bi.getWidth(); //获得 宽度
	                a[1] = bi.getHeight(); //获得 高度
	            }else{
	                a=null;
	            }
	            //删除文件
	            file.delete();
	        }else{//图片不存在
	            a=null;
	        }
	        return a;
	
	    }
	
	/**
	 * 	  new String(
	 * .getBytes(),"UTF-8")
	 * 将各种参数转换为图片，
	 *  格式为750*1334白图整合而成，
	 *  整合调整至固定规格
	 * @param goodsType 0普通商品 1 部分积分商品 2 全积分商品
	 * @param salePrice 销售价
	 * @param fullName 商品名
	 * @param mainImg 商品主图
	 * @param qrCode 二维码（商品详情H5）
	 * @param log 店铺log
	 * @param volume 销售量
	 * @param profit 收益
	 * @return 图片地址链接
	 * @author lwj
	 * @throws UnsupportedEncodingException 
	 */
	public static String handlePosterImage(Integer goodsType,String salePrice,String fullName,String mainImg,String qrCode,String log,String volume,String profit) throws UnsupportedEncodingException  {
//		//开始拼图，底图，固定，750*1334
		String botWhiteImg = "http://file.cardezu.com/lwj/white.png";//底部白色图片
		//处理参数，固定
		String watermark3 = "watermark/3";//模式3，混合水印
		String image  = "/image/";
		String text  = "/text/";
		String qMark = "?";//问号连接符
		
		//上方主图
		//图片处理参数
		String imageView2 = "imageView2/0/w/750/h/750";//处理图片参数，750*750
//		String mainImg = "http://file.cardezu.com/lwj/105538913.jpg";//传到库里的上方主图，800*800 ！！！入参
		String viewMainImg = mainImg + qMark + imageView2;//图片处理过的上方主图 缩成750*750
		String param = "/gravity/North/dy/0/dx/0";
		StringBuffer handleMainImg = new StringBuffer();//总url
		handleMainImg.append(botWhiteImg + qMark + watermark3 + 
							   image + Base64Util.safeUrlBase64Encode(viewMainImg) + param);
		//价格红图
		String priceImg = "http://file.cardezu.com/lwj/price2x.png";//固定
		String param2 = "/gravity/SouthWest/dy/585/dx/0";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(priceImg) + param2);
		
	//	// 二维码图片地址
//		String qrCode = "http://baidu.com";//！！！入参
		String urlShareQrcode = "http://qr.liantu.com/api.php?m=5&w=" + 195 + "&h=" + 195 + 
				"&logo=http://file.cardezu.com/lwj/kalian_logo1.png&text=" + qrCode;//固定
		String param3 = "/gravity/SouthEast/dy/189/dx/50";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(urlShareQrcode) + param3);
		//商铺log，必须200px*67px
//		String log = "http://file.cardezu.com/lwj/basics_xiaoe1.png";//店铺log！！！入参
		String logImageView2 = "imageView2/0/w/200/h/67";
		String param4 = "/gravity/SouthWest/dy/471/dx/35";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(log+qMark+logImageView2) + param4);
		
		if(goodsType!=null) {
			if(goodsType.intValue()==1) {
//				String priceText = "销售价";//商品价格文字//！！！固定
//				String textParam1 = "/fontsize/700/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/692/dx/89";//大小600，白色
//				handleMainImg.append(text + Base64Util.safeUrlBase64Encode(priceText) + textParam1);
				
				String price = "￥"+salePrice;//商品价格//！！！入参
				String textParam2 = "/fontsize/600/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/650/dx/15";//大小700，白色
				handleMainImg.append(text + Base64Util.safeUrlBase64Encode(price) + textParam2);
				
			}else if(goodsType.intValue()==2) {//全积分
				
				String price = salePrice;//商品价格//！！！入参
				String textParam2 = "/fontsize/800/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/650/dx/35";//大小700，白色
				handleMainImg.append(text + Base64Util.safeUrlBase64Encode(price) + textParam2);
				
			}else {
				String priceText = "销售价";//商品价格文字//！！！固定
				String textParam1 = "/fontsize/700/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/692/dx/89";//大小600，白色
				handleMainImg.append(text + Base64Util.safeUrlBase64Encode(priceText) + textParam1);
				
				String price = "￥"+salePrice;//商品价格//！！！入参
				String textParam2 = "/fontsize/800/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/625/dx/89";//大小700，白色
				handleMainImg.append(text + Base64Util.safeUrlBase64Encode(price) + textParam2);
				
			}
		}
	
		String goodsName = fullName;//商品名称,商品名字两行左右做省略号，一行10个字符//！！！入参
		String subGoodsName = StringBoUtil.handleStrLineAndSub(goodsName, 10, 19);//处理字符串每多少个加换行符(insert) 处理字符串每多少个换省略号(substring)
		String textParam3 = "/fontsize/800/gravity/NorthWest/dy/951/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(subGoodsName) + textParam3);
		
		String goodsVolume = "销量"+volume+"件";//销量//！！！入参
		String textParam4 = "/fontsize/700/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/SouthWest/dy/223/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsVolume) + textParam4);
		
		//判断是否为
		if(new BigDecimal(profit).compareTo(new BigDecimal(0))>0) {
			
			String goodsProfitText = "收益";//收益文字//！！！固定
			String textParam5 = "/fontsize/800/gravity/SouthWest/dy/135/dx/35";//大小700，白色
			handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsProfitText) + textParam5);
			
			String goodsProfit = "￥"+profit;//收益金额//！！！入参
			String textParam6 = "/fontsize/800/fill/"+Base64Util.safeUrlBase64Encode("#FF0000")+"/gravity/SouthWest/dy/135/dx/120";//大小700，白色
			handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsProfit) + textParam6);
			 
		}
		
		String qrRemark = "长按识别二维码";//二维码提示//！！！固定
		String textParam7 = "/fontsize/580/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/SouthEast/dy/135/dx/49";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(qrRemark) + textParam7);
		return handleMainImg.toString();
	}
	
	
/**
 * 网申主图
 * @param goodsType
 * @param salePrice
 * @param fullName
 * @param mainImg
 * @param qrCode
 * @param log
 * @param volume
 * @param profit
 * @return
 * @throws UnsupportedEncodingException
 */
	public static String handlePosterImageByFunction(String fullName,String mainImg,String qrCode,String volume) throws UnsupportedEncodingException  {
//		//开始拼图，底图，固定，750*1334
		String botWhiteImg = "http://file.cardezu.com/lwj/white.png";//底部白色图片
		//处理参数，固定
		String watermark3 = "watermark/3";//模式3，混合水印
		String image  = "/image/";
		String text  = "/text/";
		String qMark = "?";//问号连接符


		//上方主图
		//图片处理参数
		String imageView2 = "imageView2/0/w/750/h/750";//处理图片参数，750*750
//		String mainImg = "http://file.cardezu.com/lwj/105538913.jpg";//传到库里的上方主图，800*800 ！！！入参
		String viewMainImg = mainImg + qMark + imageView2;//图片处理过的上方主图 缩成750*750
		String param = "/gravity/North/dy/0/dx/0";
		StringBuffer handleMainImg = new StringBuffer();//总url
		handleMainImg.append(botWhiteImg + qMark + watermark3 + 
							   image + Base64Util.safeUrlBase64Encode(viewMainImg) + param);
		//价格红图
		String priceImg = "http://file.cardezu.com/lwj/price2x.png";//固定
		String param2 = "/gravity/SouthWest/dy/585/dx/0";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(priceImg) + param2);
		
	//	// 二维码图片地址
//		String qrCode = "http://baidu.com";//！！！入参
		String urlShareQrcode = "http://qr.liantu.com/api.php?m=5&w=" + 195 + "&h=" + 195 + 
				"&text=" + qrCode;//固定
		String param3 = "/gravity/SouthEast/dy/189/dx/50";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(urlShareQrcode) + param3);
		
		String goodsName = fullName;//商品名称,商品名字两行左右做省略号，一行10个字符//！！！入参
		String subGoodsName = StringBoUtil.handleStrLineAndSub(goodsName, 10, 19);//处理字符串每多少个加换行符(insert) 处理字符串每多少个换省略号(substring)
		String textParam3 = "/fontsize/800/gravity/NorthWest/dy/951/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(subGoodsName) + textParam3);
		
		String goodsVolume = "已下卡"+volume+"张";//销量//！！！入参
		String textParam4 = "/fontsize/700/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/SouthWest/dy/223/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsVolume) + textParam4);
		
		String qrRemark = "长按识别二维码";//二维码提示//！！！固定
		String textParam7 = "/fontsize/580/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/SouthEast/dy/135/dx/49";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(qrRemark) + textParam7);
		return handleMainImg.toString();
	}
    public static void main(String[] args) throws UnsupportedEncodingException {
//    	Long aa = System.currentTimeMillis();
//    	1147.50459.00阿奇特简约吊扇灯  美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯
//    	https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg
//    		http://waptest.cardezu.com/wap/outer/share/share?xiaoeWord=￥O72KYAaFhDZ￥%26fullName=阿奇特简约吊扇灯  美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯%26sourceType=2%26tbPicIndex=https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg%26merchantId=95834
//    			17
//    			null
//    	String str = handleTBPosterImage("1147.50", "459.00", 
//    			"阿奇特简约吊扇灯  美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯",
//    			"https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg",
//    			"http://waptest.cardezu.com/wap/outer/share/share?xiaoeWord=￥O72KYAaFhDZ￥%26fullName=阿奇特简约吊扇灯  美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯%26sourceType=2%26tbPicIndex=https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg%26merchantId=95834", 
//    			17,null );
//		System.out.println(str);
		
		String str = handlePosterImage(2, "100.00积分", "测试商品美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯", 
				"https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg"
				, "http://waptest.cardezu.com/wap/outer/share/share?xiaoeWord=￥O72KYAaFhDZ￥%26fullName=阿奇特简约吊扇灯  美式木叶餐厅卧室客厅风扇灯 LED变光风扇吊灯%26sourceType=2%26tbPicIndex=https://img.alicdn.com/i1/2455959824/TB2pwnPbAfb_uJjSsrbXXb6bVXa_!!2455959824.jpg%26merchantId=95834" 
				, "http://file.cardezu.com/lwj/kalian_logo.png"
				, "964"
				, "18.2");
		System.out.println(str);
		
//		String imgLocalPathAndName = "C:\\Users\\Administrator\\Desktop\\test.jpg";
//		downloadPicture(str, imgLocalPathAndName);
//		System.out.println(System.currentTimeMillis()-aa);
	}
    public static String handleTBPosterImage(String salePrice, String finalPrice, String fullName, String mainImg,
			String qrCode, Integer volume, String coupon_info ) throws UnsupportedEncodingException {
//    	System.out.println(salePrice+finalPrice+fullName+mainImg+qrCode+volume+coupon_info);
//		//开始拼图，底图，固定，750*1334
		String botWhiteImg = "http://file.cardezu.com/lwj/white.png";//底部白色图片
		//处理参数，固定
		String watermark3 = "watermark/3";//模式3，混合水印
		String image  = "/image/";
		String text  = "/text/";
		String qMark = "?";//问号连接符
		
		//上方主图
		//图片处理参数
		String imageView2 = "imageView2/0/w/750/h/750";//处理图片参数，750*750
//		String mainImg = "http://file.cardezu.com/lwj/105538913.jpg";//传到库里的上方主图，800*800 ！！！入参
		String viewMainImg = mainImg + qMark + imageView2;//图片处理过的上方主图 缩成750*750
		String param = "/gravity/North/dy/0/dx/0";
		StringBuffer handleMainImg = new StringBuffer();//总url
		handleMainImg.append(botWhiteImg + qMark + watermark3 + 
							   image + Base64Util.safeUrlBase64Encode(viewMainImg) + param);
		
		if(CheckUtil.notNull(coupon_info)) {
			//优惠券背景红图
			String mid_red_Img = "http://file.cardezu.com/lwj/mid_red_coupon.png";//
			String param4 = "/gravity/SouthWest/dy/535/dx/230";//原585
			handleMainImg.append(image + Base64Util.safeUrlBase64Encode(mid_red_Img) + param4);
		}
		//价格红图
		String priceImg = "http://file.cardezu.com/lwj/price2x.png";//固定
		String param2 = "/gravity/SouthWest/dy/535/dx/0";//原585
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(priceImg) + param2);
		
	//	// 二维码图片地址
//		String qrCode = "http://baidu.com";//！！！入参
		String urlShareQrcode = "http://qr.liantu.com/api.php?m=1&w=" + 195 + "&h=" + 195 + 
				"&text=" + qrCode;//固定
		String param3 = "/gravity/SouthEast/dy/200/dx/35";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(urlShareQrcode) + param3);
		
		
		//商铺log，必须200px*67px
//		String log = "http://file.cardezu.com/lwj/basics_xiaoe1.png";//店铺log！！！入参
//		String logImageView2 = "imageView2/0/w/200/h/67";
//		String param4 = "/gravity/SouthWest/dy/471/dx/35";
//		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(log+qMark+logImageView2) + param4);
		
		//下方说明粉红兔
		String low_pink = "http://file.cardezu.com/lwj/low_pink.png";//
		String param5 = "/gravity/South/dy/35/dx/0";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(low_pink) + param5);
				
		
		
		String priceText = "销售价";//商品价格文字//！！！固定//原692
		String textParam1 = "/fontsize/700/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/642/dx/89";//大小600，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(priceText) + textParam1);
		
		String price = "￥"+finalPrice;//商品价格//！！！入参//原625
		String textParam2 = "/fontsize/800/fill/"+Base64Util.safeUrlBase64Encode("#FFFFFF")+"/gravity/SouthWest/dy/575/dx/89";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(price) + textParam2);
		
		String goodsName = fullName;//商品名称,商品名字两行左右做省略号，一行10个字符//！！！入参
		String subGoodsName = StringBoUtil.handleStrLineAndSub(goodsName, 10, 19);//处理字符串每多少个加换行符(insert) 处理字符串每多少个换省略号(substring)
		String textParam3 = "/fontsize/800/gravity/NorthWest/dy/800/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(subGoodsName) + textParam3);
		
		String goodsVolume = "销量"+volume+"件";//销量//！！！入参
		String textParam4 = "/fontsize/600/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/NorthEast/dy/810/dx/35";//大小700，白色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsVolume) + textParam4);
		
//		String goodsProfitText = "收益";//收益文字//！！！固定
//		String textParam5 = "/fontsize/800/gravity/SouthWest/dy/135/dx/35";//大小700，白色
//		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsProfitText) + textParam5);
//		
//		String goodsProfit = "￥"+profit;//收益金额//！！！入参
//		String textParam6 = "/fontsize/800/fill/"+Base64Util.safeUrlBase64Encode("#FF0000")+"/gravity/SouthWest/dy/135/dx/120";//大小700，白色
//		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(goodsProfit) + textParam6);
		
		String logo = "http://file.cardezu.com/lwj/kalian_logo1.png";
		String paramLogo = "/gravity/SouthWest/dy/330/dx/35";
		handleMainImg.append(image + Base64Util.safeUrlBase64Encode(logo) + paramLogo);
				
		String str1 = "卡链优品APP";
		String textParam6 = "/fontsize/700/gravity/SouthWest/dy/330/dx/75";//大小700，黑色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(str1) + textParam6);
		
		String str2 = "(长按识别二维码购买商品)";
		String textParam7 = "/fontsize/700/gravity/SouthWest/dy/290/dx/35";//大小700，黑色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(str2) + textParam7);
		
		if(CheckUtil.notNull(coupon_info)) {
			String textParam8 = "/fontsize/700/gravity/SouthWest/dy/600/dx/320";//大小700，黑色
			handleMainImg.append(text + Base64Util.safeUrlBase64Encode(coupon_info) + textParam8);
			
		}
		
		String remark1 = "二维码识别不了时，复制链接打开淘宝自动跳转";
		String textParam9 = "/fontsize/500/gravity/South/dy/110/dx/0";//大小700，黑色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(remark1) + textParam9);
		
		String remark2 = "1.长按 复制页面内完整链接     2.打开淘宝 ";
		String textParam10 = "/fontsize/500/fill/"+Base64Util.safeUrlBase64Encode("#FF0000")+"/gravity/South/dy/70/dx/3";//大小700，黑色
		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(remark2) + textParam10);
		
		 
//		String qrRemark = "长按识别二维码";//二维码提示//！！！固定
//		String textParam8 = "/fontsize/580/fill/"+Base64Util.safeUrlBase64Encode("#C0C0C0")+"/gravity/SouthEast/dy/135/dx/49";//大小700，白色
//		handleMainImg.append(text + Base64Util.safeUrlBase64Encode(qrRemark) + textParam8);
		return handleMainImg.toString();
	}
}
